import 'dart:async';

import 'package:coinbaby/common/textstyle/textstyle.dart';
import 'package:flutter/material.dart';


class SmsCounterView extends StatefulWidget {
  @override
  _SmsCounterViewState createState() => _SmsCounterViewState();
}

class _SmsCounterViewState extends State<SmsCounterView> {

  Timer _timer;
  int counter = 59;

  @override
  void initState() {
    super.initState();
    _beginTimer();
  }

  @override
  void dispose() {
    _stopTimer();
    super.dispose();
  }

  void _beginTimer() {
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) { 
      if(mounted){
        setState(() {
          counter -= 1;
        });
      }
      if(counter <= 0) _stopTimer();
    });
  }

  void _stopTimer() {
    counter = 59;
    _timer.cancel();
    _timer = null;
  }

  @override
  Widget build(BuildContext context) {
    return Text.rich(
      TextSpan(
        children: [
          TextSpan(text: "$counter", style: AppFont.textStyle(14, Colors.blue)),
          TextSpan(text: " 秒后重新发送验证码", style: AppFont.textStyle(14, Colors.grey)),
        ]
      )
    );
  }
}